library(tidyverse)
library(readr)
chic <- read_csv("ggplot2/ggModify/chicago-nmmaps.csv")
chic <- chic %>%
  mutate(year = substr(date, 1, 4))

# 1. 在图上添加水平或垂直线
#   你可能想要突出一个给定的范围或阈值，
#   这可以用geom_hline()或geom_vline()在定义的坐标上绘制一条线:
ggplot(chic, aes(x = date, y = temp, color = o3)) +
  geom_point() +
  geom_hline(yintercept = c(0, 73)) +
  labs(x = "Year", y = "Temperature (°F)")

g <- ggplot(chic, aes(x = temp, y = dewpoint)) +
  geom_point(color = "dodgerblue", alpha = .5) +
  labs(x = "Temperature (°F)", y = "Dewpoint")

g +
  geom_vline(aes(xintercept = median(temp)), size = 1.5,
             color = "firebrick", linetype = "dashed") +
  geom_hline(aes(yintercept = median(dewpoint)), size = 1.5,
             color = "firebrick", linetype = "dashed")

# 2. 斜线
#   如果你想添加一条斜率不为0或1的直线，则需要使用geom_abline()。
#   这是一个例子，如果你想添加一条回归线，使用参数截距和斜率。
reg <- lm(dewpoint ~ temp, data = chic)

g +
  geom_abline(intercept = coefficients(reg)[1],
              slope = coefficients(reg)[2],
              color = "darkorange2", size = 1.5) +
  labs(title = paste0("y = ", round(coefficients(reg)[2], 2),
                      " * x + ", round(coefficients(reg)[1], 2)))


# 3. 在图内添加一条线
#   以前的方法总是涵盖了图表面板的全部范围，
#   但有时人们只想突出显示给定的区域或使用线作为注释。
#   在本例中，geom_linerange()可以提供帮助。
g +
  ## vertical line
  geom_linerange(aes(x = 50, ymin = 20, ymax = 55),
                 color = "steelblue", size = 2) +
  ## horizontal line
  geom_linerange(aes(xmin = -Inf, xmax = 25, y = 0),
                 color = "red", size = 1)

# 或者你可以使用geom_segment()绘制斜率不为0和1的线:
g +
  geom_segment(aes(x = 50, xend = 75,
                   y = 20, yend = 45),
               color = "purple", size = 2)

# 4. 在图中添加曲线和箭头
#   geom_curve()添加曲线。直线也可以如果你想的话：
g +
  geom_curve(aes(x = 0, y = 60, xend = 75, yend = 0),
             size = 2, color = "tan") +
  geom_curve(aes(x = 0, y = 60, xend = 75, yend = 0),
             curvature = -0.7, angle = 45,
             color = "darkgoldenrod1", size = 1) +
  geom_curve(aes(x = 0, y = 60, xend = 75, yend = 0),
             curvature = 0, size = 1.5)

# 同样的geom也可以用来画箭头:
g +
  geom_curve(aes(x = 0, y = 60, xend = 75, yend = 0),
             size = 2, color = "tan",
             arrow = arrow(length = unit(0.07, "npc"))) +
  geom_curve(aes(x = 5, y = 55, xend = 70, yend = 5),
             curvature = -0.7, angle = 45,
             color = "darkgoldenrod1", size = 1,
             arrow = arrow(length = unit(0.03, "npc"),
                           type = "closed",
                           ends = "both"))
                           